<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Act extends MY_Controller {

	public function __construct()
    {
        parent::__construct();
        $this->load->model('Activity_model');
        $this->load->model('Activityenter_model'); // ss
    }
	public function index()
	{
		$type = $this->input->get('type');
		$type = isset($type) ? (int)$type : $type;
                
		$page     = _get_page();
		$pagesize = 100;
		$arrParam = array();
		$arrWhere = array('status'=>1, 'display'=>1);
		if (isset($type))
		{
			$arrParam['type'] = $type;
			$arrWhere['type'] = $type;
		}

        $workItem = _get_config('work_cat');
        $pro = $this->input->get('pro');
        if ($pro) {
        	$arrParam['pro'] = $pro;
            $arrWhere['category'] = "'".$pro."'";      
        }
                
        $get_city = $this->input->get('city');
        $this->load->model('Style_model');
        if ($get_city) 
        {
        	// 城市
            if ($get_city == '其他') {
            	$cityStr = $this->Style_model->getCityStr(); 
                $arrWhere['place not in ('] = $cityStr.')';
            }
            else 
            {
            	$arrWhere['(place'] = "'".$get_city."市' or place='".$get_city."')";
            } 
            $arrParam['city'] = $get_city;
        }
        
        $get_time = $this->input->get('orderby');
        if ($get_time) 
        {
        	$arrParam['orderby'] = $get_time;
        }
        $orderby = '';
        switch($get_time) {
        	case '1': 
            	$orderby = 'addtime desc'; 
                break;
            case '2':
                $orderby= 'innum desc';
                break;
            case '3':
                $nowTime = time();
                $arrWhere['addtime >='] = $nowTime - 3 * 24 * 3600; 
                break;
            case '4':
                $arrWhere['addtime >='] = time() - 7*24*3600;
                break;
            case '5':
                $arrWhere['addtime >='] = time() - 30*24*3600;
                break;
            default :
                $orderby = '';
                break;
                        //$arrWhere[''] = '';
        }
        
        //通告状态（1：正在进行，2：已结束）
        $expired = $this->input->get("expired");
        if (!isset($expired))
        {
        	$expired = 1;
        }
        if ($expired)
        {
        	$arrParam["expired"] = $expired;
        	if ($expired == 1)
        	{
        		$arrWhere["inendtime >= "] = time();
        	}
        	else if ($expired == 2)
        	{
        		$arrWhere["inendtime < "] = time();
        	}
        }
                
		$list = $this->Activity_model->fetch_page($page, $pagesize, $arrWhere, '*', $orderby);
		//echo $this->Activity_model->db->last_query();die;
                
                if(!empty($list['rows'])) {
                    foreach ($list['rows'] as $key => $row) {
                        // 判断登陆人是否已经报名
                        $isApply = 0; //是否报名的标记
                        $where = array(
                            'actid' => $row['id'],
                            'userid' => $this->loginID,
                        );
                        $checkInfo = $this->Activityenter_model->get_by_where($where);
                        if(!empty($checkInfo)) {
                            $isApply = 1;
                        }
                        $list['rows'][$key]['isApply'] = $isApply;
                        
                        // 时间的处理
                        $list['rows'][$key]['w_time'] = $row['begtime']&&is_numeric($row['begtime']) ? (date('Y-m-d', (int)$row['begtime'])) : ''; 
                        $list['rows'][$key]['endtime'] = date('Y-m-d', $row['inendtime']);
                    }
                }else{
                    $list['rows'] = array();
                }
                
             //   print_r($list);exit();
                $this->load->model('Style_model');
                $oCity = $this->Style_model->getShowCity();
                
		//分页
		$pagecfg = array();
		$pagecfg['base_url']     = _create_url('act', $arrParam);
		$pagecfg['total_rows']   = (isset($list['count']))?$list['count']:0;
		$pagecfg['cur_page'] = $page;
		$pagecfg['per_page'] = $pagesize;
		//$this->load->library('pagination');
		$this->pagination->initialize($pagecfg);
		$list['pages'] = $this->pagination->create_links();

		$oSysAct = _get_config('activity');
		$oSysAct_en = _get_config('activity_en');

		$result = array(
                    'list' => $list,
                    'oSysAct' => $oSysAct,
                    'oSysAct_en' => $oSysAct_en,
                    'oProperty' => $workItem,
                    'arrParam'=>$arrParam,
                    'oCity' => $oCity
                );


		$this->load->view('act',$result);
	}

	public function enterlist(){
		$aid = (int)$this->input->get('aid');

		$page     = _get_page();
		$pagesize = 120;
		$arrParam = array('aid'=>$aid);
		$arrWhere = array('actid'=>$aid);

		$o = $this->Activity_model->get_by_id($aid);
		
		$dbprefix = $this->Activity_model->db->dbprefix;
	//	$this->load->model('Activityenter_model'); // ss
		$tb = $dbprefix.'activity_enter a left join '.$dbprefix.'user b on(a.userid=b.id and b.status=1)';
		$list = $this->Activityenter_model->fetch_page($page, $pagesize, $arrWhere,'a.userid,b.nickname,b.userlogo','a.addtime desc',$tb);
		//echo $this->db->last_query();die;
		

		//分页
		$pagecfg = array();
		$pagecfg['base_url']     = _create_url('act/enterlist', $arrParam);
		$pagecfg['total_rows']   = $list['count'];
		$pagecfg['cur_page'] = $page;
		$pagecfg['per_page'] = $pagesize;
		//$this->load->library('pagination');
		$this->pagination->initialize($pagecfg);
		$list['pages'] = $this->pagination->create_links();

		$result = array(
			'list' => $list,
			'o' => $o,
			);

		$this->load->view('actenterlist',$result);
	}

	public function enter(){
		$actid = _get_key_val($this->input->post('id'),true);

		$res = array('code'=>0,'data'=>array());
		$userid = $this->loginID;

		if(!$userid)
		{
			$res['code'] = 201;
			$res['data']['msg'] = '请先登录';
			$this->view->json($res);
			exit;
		}
		//$this->load->model('Activityenter_model');  // ss
		$o = $this->Activityenter_model->get_by_where(array('userid'=>$userid,'actid'=>$actid));
		if(!$o)
		{
			$data = array('actid'=>$actid,
				'userid'=>$this->loginID,
				'nickname'=>$this->loginNickName,
				'addtime'=>time(),
				);
                      
			$this->Activityenter_model->insert($data);
                        
                        //更新报名数--ss （不限制，限制2选1）
                        $activityInfo = $this->Activity_model->get_by_where(array('id'=>$actid));
                        $activityInnum = (!empty($activityInfo['innum']))?($activityInfo['innum'] + 1):'1';
                        //名额限制
//                        if($activityInfo['actnum'] >= $activityInnum) {
//                           //在限制人数内，可以增加
//                           $this->Activity_model->update_by_id($actid, array('innum'=>$activityInnum)); 
//                           $res['code'] = 200;
//                           $res['data']['msg'] = '报名成功';
//                           $res['count'] = $activityInnum;
//                        } else {
//                           $res['code'] = 203;
//                           $res['data']['msg'] = '报名名额已满';
//                        }
                        //名额不限制
                        $this->Activity_model->update_by_id($actid, array('innum'=>$activityInnum));
                        $res['count'] = $activityInnum;
                        $res['code'] = 200;
                        $res['data']['msg'] = '报名成功';
                        
		} else  {
			$res['code'] = 202;
			$res['data']['msg'] = '已报名';
		}

		$this->view->json($res);
		exit;

	}
    
    public function actDetail($id) {
        if(empty($id)) {
            show_404();
        }
        //
        $info = $this->Activity_model->get_info_by_id($id);
        if(empty($info)) {
            show_404();
        }
        
        //通告访问量
        $this->load->service('user_service');
        $sysVisittype = _get_config('visittype');
        $this->user_service->actvisit($this->loginID,$id,$sysVisittype['act']);
        
        $list = array(); // 初始化信息
        
        // 获取发布此通告的机构或者企业的详情
        $this->load->model('Usernum_model');
        $this->load->model('Userdetail_model');
        $this->load->model('User_model');
        $insInfo['num_info'] = $this->Usernum_model->get_info_by_userid($info['userid']);
        $insInfo['detail_info'] = $this->Userdetail_model->get_info_by_userid($info['userid']);
        $insInfo = $this->User_model->get_info_by_id($info['userid']);
        
        // 获取报名的列表
        $where = array('actid'=>$info['id']);
        $field = 'id,userid';        
        $order_by = ' addtime desc';
        $signUpList = $this->Activityenter_model->get_list($where, $field, $order_by);
        $this->load->model('User_model');
        if (!empty($signUpList)) {
            foreach ($signUpList as $key=>$user) {
              $userInfo = $this->User_model->get_by_id($user['userid']);
              
                if (!empty($userInfo) && (-1 != $userInfo['status'])) {
                    $list[$key] = $userInfo; // 重新组装报名列表
                } 
            }
        }
        
        // 处理时间
        if (!empty($info) && (is_numeric($info['begtime']))) {
           $info['begtime'] = date('Y-m-d', (int)$info['begtime']);
        }
        
        // 判断登陆人是否已经报名
        $isApply = 0; //是否报名的标记
        $where = array(
        	'actid' => $id,
        	'userid' => $this->loginID,
        );
        $checkInfo = $this->Activityenter_model->get_by_where($where);
        if(!empty($checkInfo)) {
        	$isApply = 1;
        }
        $info['isApply'] = $isApply;
        
        $data = array(
            'info' => $info,
            'list' => $list,
            'count' => count($list),
            'insInfo' => $insInfo
        );
        
        $this->load->view('actdetail', $data);
    }
    

}
